package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.util.RequestContextUtil;
import com.heima.feign.clients.ArticleClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.AuthenDto;
import com.heima.model.wemedia.dtos.NewsDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsPlus;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmGreenScan;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    /**
     * TODO:查询自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        // 1 设置分页参数
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        // 2 创建wrapper准备封装条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 3 所有条件封装前，切记判空！
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getKeyword() != null) {
            wrapper.eq(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        wrapper.orderByDesc(WmNews::getPublishTime);
        Page<WmNews> pageInfo = page(page, wrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageInfo.getTotal());
        result.setData(pageInfo.getRecords());
        return result;
    }

    /**
     * TODO：文章发布->将前端参数数据存入数据库表中
     *    【1】BeanUtils.copyProperties
     *    【2】前端没给的，设置默认值
     *    【3】前端List<String> image -> 实体类String image
     *    【4】type=-1 -> 从content中提取图片
     *    【5】status=1 提交 -> 发布时间=当前时间
     * @param dto
     * @return
     */
    @Autowired
    WmGreenScan wmGreenScan;

    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        WmNews wmNews = new WmNews();
        Date date = new Date();
        // 1 dto接收前端数据->copy部分对应值到文章实体类
        BeanUtils.copyProperties(dto, wmNews);
        // 2 前端没给的，设置默认值
        wmNews.setUserId(1);//先硬性编码
        wmNews.setEnable(1);
        // 3 处理图片
        if (dto.getType() == -1) {//图片类型：自动-》从内容中获取图片-》设置到dto.images
            List<String> imgs = parseContentsImg(dto);
            dto.setImages(imgs);
            wmNews.setType(imgs.size());
        }
        String allImage=null;
        if (dto.getImages().size()>0) {//正常情况：dto.images->wmNews.images
             allImage= StringUtils.join(dto.getImages(), ",");
        }
        wmNews.setImages(allImage);
        // 状态为1(表示提交)，前端未指定发布时间-》提交就设置发布时间
        if (dto.getStatus()==1 && dto.getPublishTime()==null) {
            wmNews.setPublishTime(date);//用户直接提交->发布时间=当前时间
        }
        // TODO: 文章修改
        /*
        添加和修改两个不同的接口，最终都会调用这个方法，区别——
        添加时，前端传参dto没有文章id，经过BeanUitls.copyProperties，wmNews中也没有；
        修改时，前端传参dto中有文章id，经过BeanUitls.copyProperties，wmNews中也有
         */
        if(wmNews.getId()==null){
            wmNews.setCreatedTime(date);//没有id，说明是新增-》设置创建时间
            save(wmNews);
        }else{
            updateById(wmNews);
        }
        // TODO:文章自动审核
        wmGreenScan.greenScanContextImg(wmNews.getId());
        return ResponseResult.okResult();
    }



    // 从内容中提取图片
    public List<String> parseContentsImg(WmNewsDto dto){
        // 1 获取json字符串
        String content = dto.getContent();//JSON字符串，里面有 文本内容和图片url
        // 2 json-》Map集合
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        // 3 取value->key=image,就把值收纳进list集合，最后转成string给wmnews
        ArrayList<String> imageList = new ArrayList<>();
        for (Map map : maps) {
            if (map.get(WemediaConstants.WM_NEWS_TYPE_TYPE).equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
                imageList.add(map.get(WemediaConstants.WM_NEWS_TYPE_VALUE).toString());
            }
            if (imageList.size()>3) {
                break;
            }
        }
        return imageList;
    }

    @Autowired
    WmUserService wmUserService;
    /**
     * 文章审核-查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsDto dto) {
        Page<WmNews> wmNewsPage = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //模糊
        if (!ObjectUtils.isEmpty(dto.getTitle())) {
            wrapper.like(WmNews::getTitle,dto.getTitle());
        }
        //精确
        if (!ObjectUtils.isEmpty(dto.getStatus())) {
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        wrapper.orderByDesc(WmNews::getCreatedTime);
        Page<WmNews> pageInfo = page(wmNewsPage, wrapper);
        List<WmNews> records = pageInfo.getRecords();
        List<WmNewsPlus> wmNewsPluses = new ArrayList<>();
        for (WmNews record : records) {
            WmUser wmUser = wmUserService.getById(record.getUserId());
            WmNewsPlus wmNewsPlus = new WmNewsPlus();
            BeanUtils.copyProperties(record,wmNewsPlus);
            wmNewsPlus.setAuthorName(wmUser.getName());
            wmNewsPluses.add(wmNewsPlus);
        }
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageInfo.getTotal());
        result.ok(wmNewsPluses);
        return result;
    }

    /**
     * 查看文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult searchInfo(Long id) {
        WmNewsPlus wmNewsPlus = new WmNewsPlus();
        WmNews wmNews = getById(id);
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        wmNewsPlus.setAuthorName(wmUser.getName());
        BeanUtils.copyProperties(wmNews, wmNewsPlus);
        return ResponseResult.okResult(wmNewsPlus);
    }

    /**
     * 审核失败
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(AuthenDto dto) {
        WmNews wmNews = getById(dto.getId());
        if (!ObjectUtils.isEmpty(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        wmNews.setStatus(4);
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.DATA_NOT_PASS);
    }

    /**
     * 审核通过【同步添加文章】
     * @param dto
     * @return
     */
    @Autowired
    ArticleClient articleClient;
    @Autowired
    WmUserMapper wmUserMapper;
    @Autowired
    WmChannelMapper wmChannelMapper;
    @Override
    public ResponseResult authPass(AuthenDto dto) {
        WmNews wmNews = getById(dto.getId());
        wmNews.setStatus(4);
        if (!ObjectUtils.isEmpty(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        //审核通过，WmNews更新文章状态
        updateById(wmNews);
        //审核通过，Article添加文章
        ArticleDto articleDto = new ArticleDto();
        ApArticle article = new ApArticle();

        article.setChannelId(wmNews.getChannelId());
        article.setAuthorId(wmNews.getUserId());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        article.setAuthorName(wmUser.getName());
        article.setCreatedTime(wmNews.getCreatedTime());
        article.setImages(wmNews.getImages());
        article.setPublishTime(wmNews.getPublishTime());
        article.setTitle(wmNews.getTitle());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        article.setChannelName(wmChannel.getName());
        BeanUtils.copyProperties(article,articleDto);
        articleDto.setContent(wmNews.getContent());
        articleDto.setUserId(RequestContextUtil.get("id"));
        //审核通过，添加文章
        articleClient.saveArticle(articleDto);
        return ResponseResult.okResult();
    }

}
